package com.zhkj.txg.module.group.ui

import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.graphics.Paint
import android.text.TextUtils
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import androidx.core.view.postDelayed
import androidx.core.widget.NestedScrollView
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.viewpager2.widget.ViewPager2
import com.shuyu.gsyvideoplayer.GSYVideoManager
import com.zhkj.lib.base.ViewModelActivity
import com.zhkj.lib.http.HttpResponseStatus
import com.zhkj.lib.utils.AccountManager
import com.zhkj.lib.utils.ScreenUtil
import com.zhkj.txg.R
import com.zhkj.txg.module.group.vm.GroupDetailViewModel
import com.zhkj.txg.module.home.ui.ShopActivity
import com.zhkj.txg.module.login.ui.LoginActivity
import com.zhkj.txg.module.order.ui.group.OrderSubmitGroupActivity
import com.zhkj.txg.module.product.adapter.*
import com.zhkj.txg.module.product.entity.Group
import com.zhkj.txg.module.product.entity.ProductResponse
import com.zhkj.txg.module.product.entity.ServiceTagEntity
import com.zhkj.txg.module.product.entity.SpecPriceEntity
import com.zhkj.txg.module.product.popup.OnSpecChangeCallback
import com.zhkj.txg.module.product.popup.ProductSpecPopupWindow
import com.zhkj.txg.module.product.ui.WatcherActivity
import com.zhkj.txg.utils.ImageUtils
import com.zhkj.txg.utils.WebViewUtils
import com.zhkj.txg.utils.WebViewUtils.addImageClickListener
import kotlinx.android.synthetic.main.activity_product_detail.*
import kotlinx.android.synthetic.main.item_product_comment.*
import kotlinx.android.synthetic.main.item_product_detail.*
import kotlinx.android.synthetic.main.item_product_group_bar.*
import kotlinx.android.synthetic.main.item_product_top.*
import java.text.SimpleDateFormat
import java.util.*

class GroupDetailActivity : ViewModelActivity<GroupDetailViewModel>() {

    companion object {
        private const val PRODUCT_ID = "productId"
        fun normalProduct(context: Context, id: String) {
            val intent = Intent(context, GroupDetailActivity::class.java)
                .putExtra(PRODUCT_ID, id)
            context.startActivity(intent)
        }
    }

    //倒计时
    private var timer: Timer? = null
    private var task: TimerTask? = null
    private var remain = 0L
    private var group_id = 0
    private var shareGroupId = 0
    private var otherGroup: MutableList<Group>? = null

    private val builder: StringBuilder = StringBuilder()
    private val productSpecPopupWindow by lazy {
        ProductSpecPopupWindow(this, { specId, goodsNum -> // 立即购买按钮回调
            if (AccountManager.getToken().isEmpty()) { // 未登录，跳转登录
                LoginActivity.jump2Login(this@GroupDetailActivity)
                return@ProductSpecPopupWindow
            }
            //拼团购买
            viewModel.productLiveData.value?.response?.data?.let {
                if (shareGroupId != 0) {
                    group_id = shareGroupId
                }
                OrderSubmitGroupActivity.groupBuyNow(this, it.id, specId, goodsNum, group_id, 1, it.shareId)
            }
        }, { specId, goodsNum -> // 加入购物车回调
            if (AccountManager.getToken().isEmpty()) { // 未登录，跳转登录
                LoginActivity.jump2Login(this@GroupDetailActivity)
                return@ProductSpecPopupWindow
            }
            //单独购买
            viewModel.productLiveData.value?.response?.data?.let {
                group_id = 0
                OrderSubmitGroupActivity.groupBuyNow(this, it.id, specId, goodsNum, group_id, 0, it.shareId)
            }
        }).apply {
            // 设置切换属性时的UI变动
            setOnSpecChangeCallback(object : OnSpecChangeCallback {
                override fun onSpecChange(selectSpec: SpecPriceEntity?) {
                    if (selectSpec != null) {
                        if (shareGroupId == 0)
                            btnNotMemberBuyNow.text = "我要开团\n￥${selectSpec.group_price}"
                        else {
                            btnNotMemberBuyNow.text = "立即参与\n￥${selectSpec.group_price}"
                        }
                        btnNotMemberCart.text = "单独购买\n￥${selectSpec.price}"
                    }
                }
            })
            // 设置默认属性
            viewModel.productLiveData.value?.response?.data?.let {
//                if (it?.spec != null && it.specPrice.isNotEmpty()) initData(it.spec, it.specPrice)
//                else setEmptyData(
//                    SpecPriceEntity(
//                        0, "0", "默认", it.marketPrice, it.group_price ?: "", it.price, it.storeCount,
//                        if (it.images.isNullOrEmpty()) "" else it.images[0]
//                    )
//                )
            }
        }
    }
    private val tabAdapter = ProductAdapter().apply {
        setOnItemClickListener { _, _, position ->
            when (position) {
                1 -> {
                    val commentTop = commentView.top
                    val scrollY = commentTop - titleProduct.height
                    scrollProduct.smoothScrollTo(0, scrollY)
                }
                2 -> {
                    val detailTop = detailView.top
                    val scrollY = detailTop - titleProduct.height
                    scrollProduct.smoothScrollTo(0, scrollY)
                }
                else -> scrollProduct.smoothScrollTo(0, 0)
            }
        }
    }
    private val bannerAdapter = ProductBannerAdapter()

    override val layoutResId: Int = R.layout.activity_product_detail
    override fun setViewModel(): GroupDetailViewModel = createViewModel()
    override fun statusTitleBar(): View? = titleProduct

    override fun initUI() {
        frame_group_bar.visibility = View.VISIBLE
        frame_group_rule.visibility = View.VISIBLE
        frame_other_group.visibility = View.VISIBLE
        frame_price.visibility = View.GONE
        with(tabProduct) {
            layoutManager =
                LinearLayoutManager(this@GroupDetailActivity, LinearLayoutManager.HORIZONTAL, false)
            adapter = tabAdapter
        }
        scrollProduct.setOnScrollChangeListener(object : NestedScrollView.OnScrollChangeListener {
            private val maxChangeHeight =
                ScreenUtil.getScreenWidth(this@GroupDetailActivity) * 2 / 3

            override fun onScrollChange(
                v: NestedScrollView?,
                scrollX: Int,
                scrollY: Int,
                oldScrollX: Int,
                oldScrollY: Int
            ) {
                if (scrollY <= maxChangeHeight) {
                    val alpha = scrollY.toFloat() / maxChangeHeight * 255
                    titleProduct.setBackgroundColor(Color.argb(alpha.toInt(), 255, 255, 255))
                } else titleProduct.setBackgroundColor(Color.WHITE)
                // 判断tab的位置
                when {
                    scrollY < commentView.top - titleProduct.height -> tabAdapter.selectedPosition =
                        0
                    scrollY < detailView.top - titleProduct.height -> tabAdapter.selectedPosition =
                        1
                    else -> tabAdapter.selectedPosition = 2
                }
            }
        })
        // 设置Banner
        with(bannerProduct) {
            getChildAt(0)?.overScrollMode = View.OVER_SCROLL_NEVER
            adapter = bannerAdapter
            registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
                override fun onPageSelected(position: Int) {
                    // 判断是否滑动到特定页面
                    if (position == bannerAdapter.data.lastIndex &&
                        bannerAdapter.data.last().type == BannerUIEntity.PULL
                    ) {
                        // 滚动到商品详情
                        val detailTop = detailView.top
                        val scrollY = detailTop - titleProduct.height
                        scrollProduct.smoothScrollTo(0, scrollY)
                        // 回滚到倒数第二个item
                        bannerProduct.postDelayed(300L) {
                            currentItem = bannerAdapter.data.lastIndex - 1
                        }
                    }
                    if (bannerAdapter.data[0].type == BannerUIEntity.VIDEO && position == 0) {
                        if (!bannerAdapter.data[0].userStop) GSYVideoManager.onResume()
                    } else if (bannerAdapter.data[0].type == BannerUIEntity.VIDEO && position > 0) {
                        if (GSYVideoManager.instance().isPlaying) {
                            bannerAdapter.data[0].userStop = false
                            GSYVideoManager.onPause()
                        }
                    }
                }
            })
        }
        //团购规则详情
        frame_group_rule.setOnClickListener {
            viewModel.productLiveData.value?.response?.data?.rule_detail?.let { it1 ->
                GroupRuleActivity.start(this@GroupDetailActivity, it1)
                return@setOnClickListener
            }
        }
        // 属性查看按钮监听
        tvProductSpecName.setOnClickListener {
            showSelectSpecDialog(false)
        }
        //单独购买
        btnNotMemberCart.setOnClickListener {
            if (TextUtils.isEmpty(AccountManager.getToken())) {
                LoginActivity.jump2Login(this@GroupDetailActivity)
                return@setOnClickListener
            }
            group_id = 0
            showSelectSpecDialog(false, 2)
        }
        // 我要开团
        btnNotMemberBuyNow.setOnClickListener {
            if (TextUtils.isEmpty(AccountManager.getToken())) {
                LoginActivity.jump2Login(this@GroupDetailActivity)
                return@setOnClickListener
            }
            group_id = 0
            showSelectSpecDialog(false, 1)
        }
        // 跳转店铺首页
        ivProductHome.setOnClickListener {
            val shop = viewModel.productLiveData.value?.response?.data?.shop
            if (shop == null) toast(getString(R.string.shop_is_owner))
            else ShopActivity.open(this, shop.shopName, shop.id)
        }
        // 跳转客服
        ivCustomerService.setOnClickListener {
//            VP53Manager.getInstance().EnterChatActivity(KF_53_ARG, "1", this, null)
        }
        // 商品收藏
        ivCollectionProduct.setOnClickListener {
            if (AccountManager.getToken().isEmpty()) {
                LoginActivity.jump2Login(this)
                return@setOnClickListener
            }
            viewModel.productLiveData.value?.response?.data?.let {
                viewModel.collectGoods(AccountManager.getToken(), it.id.toLong())
            }
        }
        WebViewUtils.initWebView(webView)
        webView.addImageClickListener {
            if (!it.isNullOrEmpty()) WatcherActivity.open(this, arrayListOf(it), 0)
        }
        viewNotMember.visibility = View.VISIBLE
    }

    override fun initData() {
        if (intent.data != null) {
            intent.data?.let {
                val shareId = it.getQueryParameter("share_id")
                val productId = it.getQueryParameter("goods_id")
                val groupId = it.getQueryParameter("group_id")
                if (!TextUtils.isEmpty(groupId)) {
                    shareGroupId = groupId?.toInt() ?: 0
                }
                viewModel.getProduct(productId ?: "", shareId?.toInt() ?: 0)
                return
            }
        }
        val productId = intent.getStringExtra(PRODUCT_ID)
        if (productId.isNullOrEmpty()) {
            toast(getString(R.string.product_id_error))
        } else viewModel.getProduct(productId)
    }

    override fun initViewModel() {
        viewModel.productLiveData.observe(this, Observer { it ->
            handlerResponseStatus(it.status, it.statusTip)
            if (it.status == HttpResponseStatus.Status.SUCCESS)
                it.response?.let { fillData(it) }
        })
//        viewModel.addCartLiveData.observe(this, Observer {
//            handlerResponseStatus(it.status, it.statusTip)
//            if (it.status == HttpResponseStatus.Status.SUCCESS)
//                toast(getString(R.string.add_cart_success))
//            RxBus.post(CartRefreshEvent())
//            if (productSpecPopupWindow.isShowing) productSpecPopupWindow.dismiss()
//        })
        // 商品收藏观察者
        viewModel.collectProductLiveData.observe(this, Observer { response ->
            handlerResponseStatus(response.status, response.statusTip)
            if (response.status == HttpResponseStatus.Status.SUCCESS)
                viewModel.productLiveData.value?.response?.data?.let {
                    it.isCollect = it.isCollect.not()
                    val drawable =
                        getDrawable(if (it.isCollect) R.drawable.ic_product_collection_selected else R.drawable.ic_product_collection)?.apply {
                            setBounds(0, 0, intrinsicWidth, intrinsicHeight)
                        }
                    ivCollectionProduct.setCompoundDrawables(null, drawable, null, null)
                    ivCollectionProduct.text =
                        getString(if (it.isCollect) R.string.collection_success else R.string.collection_product)
                    toast(getString(if (it.isCollect) R.string.collection_success else R.string.collection_not_success))
                }
        })

    }

    override fun onPause() {
        super.onPause()
        GSYVideoManager.onPause()
    }

    private fun fillData(resp: ProductResponse) {
        with(resp.data) {
            tvProductPrice.text = "￥${price}"
            tvProductEarn.text = "￥${marketPrice}"
            tvProductSale.text = "销量:${saleCount}"
            tvProductName.text = goodsName
            tvProductLocation.text = location
            tvProductSellTag.visibility =
                if (TextUtils.equals(isHot, "1")) View.VISIBLE else View.GONE
            tvProductNewTag.visibility =
                if (TextUtils.equals(isNew, "1")) View.VISIBLE else View.GONE
            // 判断服务Tag是否显示
            if (service.isEmpty()) btnService.visibility = View.GONE
            if (service.isNotEmpty()) tvProductService.text = getServiceText(service)
            // 判断排名是否显示
            if (rank <= 0) btnProductRank.visibility = View.GONE
            if (rank > 0) tvProductRank.text = "天兴购销售排行榜NO.${rank}"
            // 判断规格选项是否显示
            if (specPrice.isEmpty()) btnSpec.visibility = View.GONE
            if (specPrice.isNotEmpty()) tvProductSpecName.text = specPrice[0].keyName

            // 判断是否显示评论列表
            if (comment != null) {
                rvComment.layoutManager = LinearLayoutManager(this@GroupDetailActivity)
                rvComment.adapter = ProductCommentAdapter().apply {
                    setNewData(mutableListOf(comment))
                }
            } else commentTitle.visibility = View.GONE
            // 构造数据
            val list = mutableListOf<BannerUIEntity>()
            if (video.isNotEmpty()) list.add(BannerUIEntity(BannerUIEntity.VIDEO, video, images[0]))
            images.forEach { list.add(BannerUIEntity(BannerUIEntity.IMAGE, null, it)) }
            if (list.isNotEmpty()) {
                list.add(BannerUIEntity(BannerUIEntity.PULL, null, null))
                bannerProduct.offscreenPageLimit = list.size
            }
            bannerAdapter.setNewData(list)
            // 判断是否显示店铺
            if (shop != null) {
                shopView.visibility = View.VISIBLE
                tvShopName.text = shop.shopName
                ImageUtils.loadCircleImage(this@GroupDetailActivity, ivShop, shop.shopImg)
                rvShopGoods.layoutManager = LinearLayoutManager(
                    this@GroupDetailActivity,
                    LinearLayoutManager.HORIZONTAL,
                    false
                )
                rvShopGoods.adapter = ProductShopGoodsAdapter().apply {
                    setNewData(shop.shopGoods)
                }
            } else shopView.visibility = View.GONE
            // 显示详情页
            WebViewUtils.loadFullScreenHtml(webView, goodsContent)
            text_count.text = "${people}人\n拼团"
            text_price.text = "￥${group_price}"
            text_earn.apply {
                if (AccountManager.isMember() && share_earn.isNotEmpty() && share_earn != "0") {
                    paint.flags = Paint.ANTI_ALIAS_FLAG
                    text = "赚${share_earn}"
                } else {
                    paint.flags = Paint.STRIKE_THRU_TEXT_FLAG
                    paint.isAntiAlias = true
                    text = "￥${marketPrice}"
                }
            }
            countDown(last_time)
            text_rule.text = rule_brief

            if (shareGroupId == 0) {
                frame_other_group.removeAllViews()
                otherGroup = other_group
                for (item in other_group) {
                    frame_other_group.addView(getOtherView(item))
                }
                btnNotMemberBuyNow.text = "我要开团\n￥${group_price}"
            } else {
                btnNotMemberBuyNow.text = "立即参与\n￥${group_price}"
            }
            btnNotMemberCart.text = "单独购买\n￥${price}"
            // 判断是否已收藏
            val drawable =
                getDrawable(if (isCollect) R.drawable.ic_product_collection_selected else R.drawable.ic_product_collection)?.apply {
                    setBounds(0, 0, intrinsicWidth, intrinsicHeight)
                }
            ivCollectionProduct.setCompoundDrawables(null, drawable, null, null)
            ivCollectionProduct.text =
                getString(if (isCollect) R.string.collection_success else R.string.collection_product)
        }
    }

    private fun getOtherView(item: Group): View? {
        val view: View = layoutInflater.inflate(R.layout.item_other_group, null)
        ImageUtils.loadCircleImage(
            this@GroupDetailActivity,
            (view.findViewById<View>(R.id.image_avatar) as ImageView),
            item.avatar
        )
        view.findViewById<TextView>(R.id.text_group_remain).text = "还差${item.diff}人成团"
        // 去参团
        view.findViewById<TextView>(R.id.text_create).setOnClickListener {
            group_id = item.id.toInt()
            showSelectSpecDialog(false, 1)
        }

        return view
    }

    private fun refreshOtherView(past: Long) {
        if (otherGroup != null) {
            var i = 0
            if (frame_other_group.childCount == 0) return
            val sdf = SimpleDateFormat("HH:mm:ss")
            for (item in otherGroup!!) {
                val temp = if (item.last_time < past) 0 else (item.last_time - past) * 1000
                val textView: TextView =
                    frame_other_group.getChildAt(i).findViewById(R.id.text_leave)
                runOnUiThread {
                    sdf.timeZone = TimeZone.getTimeZone("GMT")
                    textView.text =
                        "剩余${if (temp > 86400000) "${temp / 86400000}天" else ""}${sdf.format(temp)}"
                }
                i++
            }
        }

    }

    private fun countDown(time: Long) {
        if (timer == null) {
            timer = Timer()
        }

        task = object : TimerTask() {
            var second = 0L
            var minute = 0L
            var hour = 0L
            override fun run() {
                if (remain > 0) {
                    second = remain % 60
                    minute = remain / 60 % 60
                    hour = remain / 3600 % 24
                    runOnUiThread {
                        text_second.text = if (second >= 10) "${second}" else "0${second}"
                        text_minute.text = if (minute >= 10) "${minute}" else "0${minute}"
                        text_hour.text = if (hour >= 10) "${hour}" else "0${hour}"
                        text_day.text = "${remain / 3600 / 24}"
                    }

                    refreshOtherView(time - remain)
                } else {
                    task?.cancel()
                }
                remain--
            }
        }
        remain = time
        timer?.schedule(task, 0, 1000)
    }


    private fun getServiceText(service: MutableList<ServiceTagEntity>): String {
        builder.setLength(0)
        for (serviceTag in service) builder.append(serviceTag.title).append(" ")
        return builder.toString()
    }

    private fun showSelectSpecDialog(isBuy: Boolean, groupType: Int = 0) {
        productSpecPopupWindow.setMode(isBuy, groupType)
        productSpecPopupWindow.showPopupWindow()
    }

    override fun onDestroy() {
        super.onDestroy()
        GSYVideoManager.releaseAllVideos()
        if (timer != null) {
            timer = null
        }
        if (task != null) {
            task?.cancel()
            task = null
        }
    }
}